import ctypes
import inspect
import json
import os
import shutil
import sys
import time
import unittest
import threading
from PIL import Image, ImageTk, ImageSequence
import requests
import tkinter as tk
import source_preservation as SOU
import HTMLTestRunner
from logConfig import LogCustom
from yaml_RW import YamlRW
import ddt
# from test_case_GMB import TestCaseForGMB

MS = ''

def get_file_path(root_path, file_list):
    for dir_file in os.listdir(root_path):
        # 获取目录或者文件的路径
        dir_file_path = os.path.join(root_path, dir_file)
        # 判断该路径为文件还是路径
        if os.path.isfile(dir_file_path):
            file_list.append(dir_file_path)
        else:
            get_file_path(dir_file_path, file_list)

def get_driver_param_list(path1,path2):
    file_list1 = []
    file_list2 = []
    if os.path.exists(os.path.join(path1, 'temp')):
        shutil.rmtree(os.path.join(path1, 'temp'))
        os.makedirs(os.path.join(path1, 'temp'))
    else:
        os.makedirs(os.path.join(path1, 'temp'))
    if os.path.exists(os.path.join(path2, 'temp')):
        shutil.rmtree(os.path.join(path2, 'temp'))
        os.makedirs(os.path.join(path2, 'temp'))
    else:
        os.makedirs(os.path.join(path2, 'temp'))
    get_file_path(path1, file_list1)
    get_file_path(path2, file_list2)
    file_list1.sort()
    file_list2.sort()
    for file_path in file_list1:
        shutil.copy2(file_path, os.path.join(path1, f'temp\\{os.path.basename(file_path)}'))
    for file_path in file_list2:
        shutil.copy2(file_path, os.path.join(path2, f'temp\\{os.path.basename(file_path)}'))

    pa = list(set([os.path.basename(_) for _ in file_list1] + [os.path.basename(_) for _ in file_list2]))
    pa.sort()
    list1 = [[os.path.join(path1, f'temp\\{_}'), os.path.join(path2, f'temp\\{_}')] for _ in pa]
    return list1
    # print(json.dumps(list1,ensure_ascii=False,indent=2))
    # print(len(list1))
def run(path1,path2):
    if os.path.exists(path1) and os.path.exists(path1):
        LogCustom().info('开始对比股名表！')
        # if os.path.exists(f'{os.path.dirname(sys.argv[0])}/testCaseDriver.yaml') == False:
        #     with open(f'{os.path.dirname(sys.argv[0])}/testCaseDriver.yaml', 'w') as a:
        #         pass
        if os.path.exists(f'{os.path.dirname(sys.argv[0])}/reports') == False:
            os.mkdir(f'{os.path.dirname(sys.argv[0])}/reports')
        # if os.path.exists(f'{os.path.dirname(sys.argv[0])}/ddt.py') == False:
        #     with open(file=f'{os.path.dirname(sys.argv[0])}/ddt.py',mode='w',encoding='utf-8') as a:
        #         a.write(SOU.DDT)
        if os.path.exists(f'{os.path.dirname(sys.argv[0])}/test_case_GMB.py') == False:
            with open(file=f'{os.path.dirname(sys.argv[0])}/test_case_GMB.py',mode='w',encoding='utf-8') as a:
                a.write(SOU.GMB)
        resp = requests.request('get', 'http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp')
        NOW = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime(int(resp.json()['data']['t'][:-3])))

        YamlRW(f'{os.path.dirname(sys.argv[0])}/testCaseDriver.yaml').wightYaml(get_driver_param_list(path1,path2))
        # suit = unittest.TestSuite()
        suit = unittest.defaultTestLoader.discover(os.path.dirname(sys.argv[0]), '*GMB.py')
        # print(json.dumps(unittest.TestLoader().getTestCaseNames(TestCaseForGMB),ensure_ascii=False,indent=2))
        # for temp in unittest.TestLoader().getTestCaseNames(TestCaseForGMB):
        #     suit.addTest(TestCaseForGMB(temp))
        reportname = f'{os.path.dirname(sys.argv[0])}/reports/TestResult_' + NOW + '.html'
        with open(reportname, 'wb') as f:
            runner = HTMLTestRunner.HTMLTestReport(
                stream=f,
                tester='李书凡',
                title='股名表对比',
                description=MS
            ).run(suit)
        # os.remove(f'{os.path.dirname(sys.argv[0])}/testCaseDriver.yaml')
        LogCustom().info('股名表对比结束！')
    elif not os.path.exists(path1):
        LogCustom().info('股名表目录一不存在！')
    elif not os.path.exists(path2):
        LogCustom().info('股名表目录二不存在！')

# threadingCreatrCase = threading.Thread(target=createCase, args=())
# threadingRun = threading.Thread(target=run, args=())

def start():
    if os.path.exists(f'{os.path.dirname(sys.argv[0])}/0.gif') == False:
        with open(file=f'{os.path.dirname(sys.argv[0])}/0.gif', mode='wb') as a:
            a.write(SOU.GIF)
    def runTh():
        # test_package1 = entry_file.get()
        # test_package2 = entry_create_according_to_file.get()
        # threadingRun.daemon = True
        # run(entry_create_according_to_file.get(),entry_file.get())
        threading.Thread(target=run, args=(entry_create_according_to_file.get(),entry_file.get())).start()


    # 第1步，实例化object，建立窗口window
    window = tk.Tk()

    # 第2步，给窗口的可视化起名字
    window.title('Wellcome to F10 Auto Regression Test')

    # 第3步，设定窗口的大小(长 * 宽)
    window.geometry('900x500')  # 这里的乘是小x

    if os.path.exists(f'{os.path.dirname(sys.argv[0])}/0.gif'):
        # 第4步，加载 wellcome image
        canvas = tk.Canvas(window, width=900, height=500, bg='green')
        image_file = tk.PhotoImage(file=f'{os.path.dirname(sys.argv[0])}/0.gif')
        image = canvas.create_image(450, 0, anchor='n', image=image_file)
        canvas.pack(side='top')

        def pick(event):
            global a, flag
            while 1:
                im = Image.open(f'{os.path.dirname(sys.argv[0])}/0.gif')
                # GIF图片流的迭代器
                iter = ImageSequence.Iterator(im)
                # frame就是gif的每一帧，转换一下格式就能显示了
                for frame in iter:
                    pic = ImageTk.PhotoImage(frame)
                    canvas.create_image((450, 250), image=pic)
                    time.sleep(0.01)
                    window.update_idletasks()  # 刷新
                    window.update()
        # window.attributes("-alpha", 0.2)
        canvas.bind("<Enter>", pick)

    tk.Label(window, text='股名表目录一:', font=('楷体', 17),bg='#00ffcc').place(x=60, y=20)

    var_create_according_to_file = tk.StringVar()
    # var_create_according_to_file.set('/Users/far/Desktop/0712股名表对比/0712股名表全真')
    entry_create_according_to_file = tk.Entry(window, textvariable=var_create_according_to_file,
                                              font=('Times New Roman', 17), width=40,bd='2',)
    entry_create_according_to_file.place(x=60, y=52)

    tk.Label(window, text='测试描述:', font=('楷体', 17), bg='#00ffcc').place(x=530, y=20)

    var_MS = tk.StringVar()
    entry_MS = tk.Entry(window, textvariable=var_MS, font=('Times New Roman', 17), width=30, bd=2)
    entry_MS.place(x=530, y=52, height=110)
    MS = entry_MS.get()

    tk.Label(window, text='股名表包目录二:', font=('楷体', 17),bg='#00ffcc').place(x=60, y=100)

    var_file = tk.StringVar()
    # var_file.set('/Users/far/Desktop/0712股名表对比/AllStock生产')
    entry_file = tk.Entry(window, textvariable=var_file, font=('Times New Roman', 17), width=40,bd='2')
    entry_file.place(x=60, y=132)

    btn_sign_up = tk.Button(window, text='开始对比股名表',font=('黑体', 30),cursor='hand2',bd='5',relief="raised",command=runTh)
    btn_sign_up.place(x=300, y=360, width=300, height=50)


    # 第10步，主窗口循环显示
    window.mainloop()


if __name__ == '__main__':

    start()
